<template>
    <div class="header">
        <!-- 头部左侧Logo和标题 -->
        <a href="#">
            <img class="logo" src="@/assets/vue.svg" width="25px"></img>
            <span class="company">学员管理系统</span>
        </a>
        <el-dropdown @command="handleCommand" trigger="click">
            <span class="el-dropdown-link">
                {{ userName }}
                <el-icon class="el-icon--right">
                    <arrow-down />
                </el-icon>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item command="a">修改密码</el-dropdown-item>
                    <el-dropdown-item command="b">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <span class="date">
            {{ currentTime }}

        </span>

        <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
            <el-form :model="userForm" ref="userFormRef" label-width="100px" label-position="right" :rules="rules">
                <!-- prop中的值是用来在rules规则校验的时候使用 -->
                <el-form-item label="原始密码" prop="oldPass">
                    <el-input v-model="userForm.oldPass" type="password" />
                </el-form-item>
               <el-form-item label="新密码" prop="pass">
                    <el-input v-model="userForm.pass" type="password" />
                </el-form-item>
               <el-form-item label="确认密码" prop="checkPass" >
                    <el-input v-model="userForm.checkPass" type="password" @keydown.enter="updatePwd(userFormRef)"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    
                    <el-button type="primary" @click="updatePwd(userFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue';
import { ref, onMounted, reactive } from 'vue';
import { formateTime } from '@/utils/dateUtils';
import useUserStore from '@/store/modules/user'
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { reqCheckPwd, reqUpdatePwd } from '@/api/user';
import { ElMessage } from "element-plus";
const $router = useRouter();
const userStore = useUserStore();
const handleCommand = (command: string) => {
    switch (command) {
        case 'a':
            //修改密码
            dialogFormVisible.value = true;
            break;
        case 'b':
            //退出登录
            Logout();
            break;
        default:
            break;
    }
}
const Logout = () => {
    userStore.removeLogout();
    $router.replace("/login")
}
let currentTime = ref<string>('');
const getTime = () => {
    setInterval(() => {
        currentTime.value = formateTime(Date.now());
    })
}
onMounted(() => {
    getTime()
})

let userName = ref(useUserStore().user?.name);

//修改密码弹出是否展示
const dialogFormVisible = ref(false);
//修改密码表达数据收集对象
const userForm = reactive({
    oldPass:"",
    pass:"",
    checkPass:""
})
//表达式ref对象
const userFormRef = ref()

//校验规则
const validateOldPass = (rule: any, value: any, callback: any) => {
  reqCheckPwd({userId:userStore.user?._id as string,password:value}).then(res=>{
    if(res.status == 0){
        callback()
    }else{
        callback(new Error(res.msg))
    }
  })
}
const validateCheckPass = (rule: any, value: any, callback: any) => {
  if(value !== userForm.pass){
    callback(new Error("两次密码不一致"))
  }else{
    callback()
  }
}

//修改密码表单校验规则
const rules = reactive<FormRules>({
    oldPass:[{required:true,validator:validateOldPass,trigger:"blur"}],
    pass:[{required:true,message:"请输入新密码",trigger:"blur"}],
    checkPass:[{required:true,validator:validateCheckPass,trigger:"blur"}],
})

//确定按钮点击回调函数
const updatePwd = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //调用接口修改密码
      reqUpdatePwd({userId:userStore.user?._id as string,password:userForm.pass}).then(res=>{
        //修改成功
        if(res.status == 0){
            //退出登录
            Logout()
            //关闭对话框
            dialogFormVisible.value = false
            //提示修改成功
            ElMessage({
            message: "修改密码成功",
            type: "success",
        });
        }
      })
    } else {
      console.log('error submit!')
    }
  })
}
</script>
<style>
.logo {
    vertical-align: middle;
    padding: 0 10px 0 40px;
}

.company {
    position: absolute;
    color: white;
}

/* 下拉菜单 */
.el-dropdown {
    float: right;
    margin-right: 40px;
    height: 50px;
    line-height: 50px;
}

.el-dropdown-link {
    cursor: pointer;
    color: #fff;
}

.date {
    float: right;
    color: #fff;
    margin-right: 50px;
}
</style>